package com.etc.reflectdemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestPerson3 {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        //得到Person.class
        Class<Person> personClass = Person.class;

        // 1 getDeclaredConstructors => Constructor<?>[]
        //所有构造方法包括私有
        System.out.println("*************getDeclaredConstructors*************");
        Constructor<?>[] declaredConstructors = personClass.getDeclaredConstructors();

        for (Constructor m : declaredConstructors) {
            //Constructor
            System.out.println(m.getName() + " " + m.getModifiers());
        }

        System.out.println("*************getMethods*************");
        //得到的是公共的构造方法
        Constructor<?>[] constructors = personClass.getConstructors();

        for (Constructor m : constructors) {
            //Constructor
            System.out.println(m.getName() + ": " + m.getModifiers());
        }

        System.out.println("*************getDeclaredMethod,调用invoke方法*************");
        //拿到一个Integer类型参数的构造方法
        Constructor<Person> declaredConstructor = personClass.getDeclaredConstructor(Integer.class);

        //私有的方法可以访问
        declaredConstructor.setAccessible(true);
        //调用构造方法创建对象，并初始化id
        Person person = declaredConstructor.newInstance(123);
        System.out.println(person);

    }
}
